from flask import Blueprint,render_template,request,jsonify,redirect,session,url_for
from utils import db
from . import input_info

bi = Blueprint('bill', __name__)

# 支付状态字典
bill_status_dict ={
        0:{'text':'未支付','cls':'danger'},
        1:{'text':'已支付','cls':'success'},
    }

# 定义日期格式
date_format = "%Y-%m-%d"

# 账单列表
@bi.route('/bill/list',methods=['GET'])
def bill_list():
    user_info = session.get('user_info')
    if user_info['role'] == 2:
        bill_list = db.get_all("SELECT * FROM bill")
        return render_template("bill_list.html",bill_list=bill_list,bill_status_dict=bill_status_dict)
    elif user_info['role'] == 1:
        bill_list = db.get_all("SELECT bill.* FROM user JOIN bill ON user.remark = bill.remark WHERE user.ID = %s",(user_info['ID'],))
        return render_template("bill_list.html",bill_list=bill_list,bill_status_dict=bill_status_dict)
    else:
        return redirect(url_for('view.login'))
    
# 添加账单
@bi.route("/bill", methods=["POST"])
def add_bill():
    user_info = session.get("user_info")
    if user_info['role'] == 2:
        bill_data = input_info.input_bill_info()
        result = input_info.norm_bill_info()
        if 'success' in result and result['success'] == True:
            # 在添加账单之前进行数据库备份
            backup_result = db.backup_database()
            if '成功' not in backup_result:
                return render_template('bill_list.html', error=f'数据库备份失败: {backup_result}')
            
            add_bill_sql = '''
                INSERT INTO bill(remark,debt_date,goods,cargo_quantity,price,total_arrears,bill_status)
                VALUES(%s,%s,%s,%s,%s,%s,0)
            '''
        try:
            db.execute(add_bill_sql, [bill_data['remark'], bill_data['debt_date'], bill_data['goods'],
                                      bill_data['cargo_quantity'], bill_data['price'], bill_data['total_arrears']])
            return jsonify({'success': True, 'msg': '添加成功'})
        except Exception as e:
            return jsonify({'success': False, 'msg': f'添加失败：{str(e)}'})
    else:
        return jsonify({'success': False, 'msg': '权限不足'})
# 已付款账单
@bi.route("/bill/<id>/update_status",methods=["PUT"])
def update_bill_status(id):
    user_info = session.get("user_info")
    if user_info['role'] == 2:
        bill_list = db.get_one("SELECT * FROM bill WHERE id = %s",[id])
        if bill_list['bill_status'] == 0:
            bill_status = request.json.get("bill_status")
            payment_date = request.json.get("payment_date")
            update_bill_status_sql = "UPDATE bill SET bill_status =%s,payment_date=%s WHERE id = %s"
            db.execute(update_bill_status_sql,[bill_status,payment_date,id])
            return jsonify({"success":True,"msg":"修改成功"})
        else:
            return jsonify({"success":False,"msg":"已付款账单无法修改"})

# 删除账单
@bi.route("/bill/<id>",methods=['DELETE'])
def delete_bill(id):
    user_info = session.get('user_info')
    if user_info['role'] == 2:
        sql = "DELETE FROM bill WHERE id = %s and bill_status = 1"
        db.execute(sql,[id])
        return jsonify({"success":True,"msg":"删除成功"})
    else:
        return jsonify({"success":False,"msg":"权限不足"})
        
